<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <!-- 添加角色对话框 -->
        <el-dialog
            title="添加角色"
            :visible.sync="addDialogVisible"
            width="50%"
            @close="addDialogClosed">
            <el-form ref="roleFormRef" :model="addRoleForm" :rules="roleRules" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑修改角色的对话框 -->
        <el-dialog
            title="编辑角色"
            :visible.sync="editDialogVisible"
            width="50%"
            @close="editDialogClosed">
            <el-form ref="editRoleFormRef" :model="editRoleForm" :rules="roleRules" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRoleInfo">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 添加角色按钮区 -->
        <el-row>
            <el-col>
                <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
            </el-col>
        </el-row>

        <!-- 角色列表区域 -->
        <el-table :data="rolelist" border stripe>
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-row :class="['bdbottoem',i1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1,i1) in props.row.children" :key="item1.id">
                        <!-- 渲染一级权限 -->
                        <el-col :span="5">
                            <el-tag closable @close="removeRightById(props.row,item1.id)">{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 渲染二级和三级权限 -->
                        <el-col :span="19">
                            <!-- 渲染二级权限菜单 -->
                            <el-row :class="[i2 === 0 ? '' : 'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                <el-col :span="6">
                                    <el-tag closable type="success" @close="removeRightById(props.row,item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="18">
                                    <!-- 渲染三级权限菜单 -->
                                        <el-tag closable type="warning" v-for="item3 in item2.children" 
                                        :key="item3.id" @close="removeRightById(props.row,item3.id)">{{item3.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                    <!-- <pre>{{props.row}}</pre> -->
                </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="props">
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRole(props.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(props.row.id)">删除</el-button>
                    <el-button size="mini" type="warning" icon="el-icon-setting" @click="showRightDialog(props.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
        title="分配权限"
        :visible.sync="RightDialogVisible"
        width="50%"
        @close="setRightDialogClosed">
        <!-- 树形控件 -->
        <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" 
        default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="RightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import {rolesList,addRole,getRoleId,editRole,deleteRole,deleteRight,rightsTree,fpRights} from '@/api'
export default {
    name:'Roles',
    data() {
        return {
            //所有角色列表数据
            rolelist:[],
            // 控制添加角色对话框的显示与隐藏
            addDialogVisible:false,
            // 添加角色的表单数据
            addRoleForm:{
                roleName:'',
                roleDesc:''
            },
            roleRules:{
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                ],
            },
            // 控制编辑角色对话框的显示与隐藏
            editDialogVisible:false,
            // 编辑修改角色的表单数据
            editRoleForm:{},
            // 控制分配权限对话框的显示与隐藏
            RightDialogVisible:false,
            // 所有权限的数据
            rightslist:[],
            // 树形控件的属性绑定对象
            treeProps: {
                children: 'children',
                label: 'authName'
            },
            // 默认选中的节点的id值
            defKeys:[],
            // 当前即将分配权限的角色id
            roleId:''
        }
    },
    created(){
      this.rolesList()  
    },
    methods:{
        // 获取所有角色的列表
        rolesList(){
            // 获取所有角色的列表
            rolesList().then(({data:res})=>{
                // console.log(res);
                if(res.meta.status == 200){
                    this.rolelist = res.data 
                }else{this.$message.error('获取用户列表失败')}
            })
        },
        // 添加角色
        addRole() {
            this.$refs.roleFormRef.validate((valid) => {
                if (valid) {
                    addRole(this.addRoleForm).then(({data:res})=>{
                        // console.log(res);
                        if(res.meta.status == 201){
                            this.$message({ message: "添加角色成功", type: "success" });
                        }else{this.$message("添加角色失败");}
                    })
                    // 关闭添加用户的对话框
                    this.addDialogVisible = false;
                    //重新获取用户列表
                    this.rolesList()
                }
            });
        },
        //监听添加用户对话框的关闭事件
        addDialogClosed(){
            this.$refs.roleFormRef.resetFields(); //清空表单
        },
        // 点击编辑获取角色数据
        editRole(id){
            // console.log(id);
            getRoleId(id).then(({data:res})=>{
                this.editRoleForm = res.data
                this.editDialogVisible = true
            })
        },
        // 编辑修改角色
        editRoleInfo(){
            this.$refs.editRoleFormRef.validate((valid) => {
                if (valid) {
                    editRole(this.editRoleForm.roleId,{roleName:this.editRoleForm.roleName,roleDesc:this.editRoleForm.roleDesc}).then(({data:res})=>{
                        // console.log(res);
                        if(res.meta.status == 200){
                            this.$message({ message: "修改角色成功", type: "success" });
                        }else{this.$message("修改角色失败");}
                    })
                    // 关闭添加用户的对话框
                    this.editDialogVisible = false
                    //重新获取用户列表
                    this.rolesList()
                }
            });
        },
        editDialogClosed(){
            this.$refs.editRoleFormRef.resetFields(); //清空表单
        },
        // 删除角色
        deleteRole(id){
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {
                    deleteRole(id).then(({data:res}) => {
                        if(res.meta.status == 200){
                            this.$message({type: 'success',message: '删除成功!'});
                        }else{this.$message.error('删除失败')}
                        //重新获取用户列表
                        this.rolesList()
                    }) 
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
            });
        },
        // 根据id删除对应的权限
        removeRightById(role,rightId){
            this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(() => {
                    deleteRight(role.id,rightId).then(({data:res})=>{
                        if(res.meta.status == 200){
                            this.$message({type: 'success',message: '删除成功!'});
                        }else{this.$message.error('删除失败')}

                        // this.rolesList()
                        role.children = res.data
                    })
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });

        },
        // 展示分配权限的对话框
        showRightDialog(role){
            this.roleId = role.id
            // 获取所有权限的数据
            rightsTree().then(({data:res})=>{
                console.log(res);
                if(res.meta.status == 200){
                    // 把获取的权限数据保存到rightslist中
                    this.rightslist = res.data
                }else{this.$message.error('获取权限数据失败')}
            })
            // 递归获取三级节点的Id
            this.getLeafkey(role,this.defKeys)
            this.RightDialogVisible = true
        },
        // 通过递归的形式,获取角色下所有三级权限的id,并保存到defKeys数组中
        getLeafkey(node,arr){
            // 如果当前node节点不包含children属性,则是三级节点
            if(!node.children){
                return arr.push(node.id)
            }else{
                node.children.forEach(item => {
                    this.getLeafkey(item,arr)
                });
            }
        },
        // 监听分配权限对话框的关闭事件
        setRightDialogClosed(){
            this.defKeys = []
        },
        // 点击确定为角色分配权限
        allotRights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            // 拼接为以逗号分隔的字符串
            const idStr = keys.join(',')
            fpRights(this.roleId,{rids:idStr}).then(({data:res})=>{
                if(res.meta.status == 200){
                    this.$message({type: 'success',message: '分配权限成功!'});
                    this.rolesList()
                    this.RightDialogVisible = false
                }else{this.$message.error('分配权限失败')}
            })
        }
    }
}
</script>

<style lang="less" scoped>
    .el-tag{
        margin: 7px;
    }
    .bdtop{
        border-top: 1px solid #eee;
    }
    .bdbottoem{
        border-bottom: 1px solid #eee;
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
</style>